package org.geometerplus.android.fbreader;

import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.geometerplus.android.fbreader.util.BookSearch;
import org.geometerplus.android.fbreader.util.CollectionUtils;
import org.geometerplus.android.fbreader.util.InputMethodUtils;
import org.geometerplus.android.fbreader.util.L;
import org.geometerplus.android.fbreader.util.OnLoadListener;
import org.geometerplus.android.fbreader.util.PagerListView;
import org.geometerplus.fbreader.fbreader.ActionCode;
import org.geometerplus.fbreader.fbreader.FBReaderApp;
import org.geometerplus.zlibrary.text.model.ZLTextMark;
import org.geometerplus.zlibrary.ui.android.R;

import java.util.ArrayList;
import java.util.List;


public class SearchPopup extends PopupPanel implements View.OnClickListener {

    public static final String ID = "SearchPopup";
    int pagesize = 100000;

    EditText tv_search_content;

    FBReader activity;
    private PagerListView listView;
    private MarkAdapter adapter;
    private List<ZLTextMark> data = new ArrayList<>();
    private TextView cancelButton;

    SearchPopup(FBReaderApp fbReader) {
        super(fbReader);
    }

    @Override
    public void createControlPanel(final FBReader activity, RelativeLayout root) {
        if (myWindow != null && myWindow.getContext() == activity)
            return;

        this.activity = activity;

        activity.getLayoutInflater().inflate(R.layout.search_popup, root);

        myWindow = root.findViewById(R.id.search_panel);
        tv_search_content = root.findViewById(R.id.tv_search_content);
        listView = root.findViewById(R.id.listview);

        cancelButton = root.findViewById(R.id.cancel_search);
        cancelButton.setOnClickListener(this);

        adapter = new MarkAdapter();
        listView.setData(data, pagesize);
        listView.setAdapter(adapter);

        listView.setOnLoadListener(new OnLoadListener() {
            @Override
            public void onLoad(int pageIndex) {
                adapter.setData(listView.getPageData(pageIndex));
            }
        });
        tv_search_content.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    tv_search_content.clearFocus();
                    InputMethodUtils.hideSoftIME(activity);
                    getReader().runAction(ActionCode.SEARCH, tv_search_content.getText().toString());
                }
                return false;
            }
        });
    }

    public void setData(List<ZLTextMark> data) {
        this.data.clear();
        if (CollectionUtils.isNotEmpty(data)) {
            this.data.addAll(data);
            cancelButton.setText("取消");
            tv_search_content.setEnabled(false);
            tv_search_content.setFocusable(false);
        }

        listView.setData(this.data, pagesize);
        listView.reLoad();
    }

    class MarkAdapter extends BaseAdapter {

        List<ZLTextMark> mData = new ArrayList<>();

        public MarkAdapter() {
        }

        public void setData(List<ZLTextMark> data) {
            mData.clear();
            if (CollectionUtils.isNotEmpty(data))
                mData.addAll(data);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public ZLTextMark getItem(int i) {
            return mData.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int position, View convertview, ViewGroup viewGroup) {

            SearchListViewHolder holder = null;

            if (convertview == null) {
                convertview = LayoutInflater.from(activity).inflate(R.layout.view_pop_search_result_item, null, false);
                holder = new SearchListViewHolder(convertview);
                convertview.setTag(holder);
            } else {
                holder = (SearchListViewHolder) convertview.getTag();
            }

            final ZLTextMark item = getItem(position);
            SpannableString contentSp = new SpannableString(item.nearContent);
            if (contentSp.length() >= (item.indexOfKeywordInString + item.Length))
                contentSp.setSpan(new ForegroundColorSpan(0x88FF0000), item.indexOfKeywordInString,
                        item.indexOfKeywordInString + item.Length, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            holder.tv_marker_content.setText(contentSp);
            holder.tv_marker_chapter.setText(getReader().getChapterTitleByParagraphNumber(item.ParagraphIndex));
            holder.rootview.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    InputMethodUtils.hideSoftIME(activity);
                    if (listener != null)
                        listener.onItemClick(item);
                    closeSearch();
                }
            });

            return convertview;
        }

        class SearchListViewHolder {
            View rootview;
            TextView tv_marker_chapter;
            TextView tv_marker_content;

            public SearchListViewHolder(View view) {
                rootview = view.findViewById(R.id.rootview);
                tv_marker_chapter = view.findViewById(R.id.tv_marker_chapter);
                tv_marker_content = view.findViewById(R.id.tv_marker_content);
            }
        }
    }

    public interface OnItemClickListener {
        void onItemClick(ZLTextMark item);
    }

    private OnItemClickListener listener;

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    public void setKeyword(String keyword) {
        if (tv_search_content != null) {
            tv_search_content.setText(keyword);
            if (keyword != null)
                tv_search_content.setSelection(keyword.length());
        }
    }

    @Override
    protected void show_() {
        data.clear();
        super.show_();
    }

    @Override
    public String getId() {
        return ActionCode.SEARCH;
    }

    @Override
    protected void update() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cancel_search:
                if ("取消".equals(cancelButton.getText().toString())) {
                    closeSearch();
                } else {
                    tv_search_content.clearFocus();
                    InputMethodUtils.hideSoftIME(activity);
                    getReader().runAction(ActionCode.SEARCH, tv_search_content.getText().toString());
                }
                break;
        }
    }

    private void closeSearch() {
        L.d("cancel search");
        Application.runAction(ActionCode.CLEAR_FIND_RESULTS);
        storePosition();
        StartPosition = null;
        Application.hideActivePopup();
        removeAllWindows(Application, activity);
        BookSearch.getInstance().cancel();
    }

    @Override
    protected void hide_() {
        super.hide_();
        Application.runAction(ActionCode.CLEAR_FIND_RESULTS);
        BookSearch.getInstance().cancel();
    }
}
